import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {
    login as apiLogin,
    getUserInfo as apiGetUserInfo,
    getUserProfile as apiGetUserProfile,
    getUserProducts as apiGetUserProducts,
    getUserFavorites as apiGetUserFavorites,
    updateUserInfo as apiUpdateUserInfo
} from '@/api/user'
import {
    updateProductStatus as apiUpdateProductStatus,
    deleteProduct as apiDeleteProduct
} from '@/api/product'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

// 添加防抖控制，记录最近的请求和响应
const userProductsRequestCache = new Map();
const REQUEST_CACHE_TIMEOUT = 500; // 毫秒

export const useUserStore = defineStore('user', () => {
    // 状态
    const token = ref(localStorage.getItem('token') || '')
    const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
    const products = ref<any[]>([])
    const productsLoading = ref(false)
    const productsTotal = ref(0)
    const cart = ref<any[]>([])
    const favorites = ref<any[]>([])
    const favoritesLoading = ref(false)
    const favoritesTotal = ref(0)
    const chatList = ref<any[]>([])
    const unreadCount = ref(0)
    const walletBalance = ref(0)

    // 计算属性
    const isLoggedIn = computed(() => !!token.value)
    const isSeller = computed(() => userInfo.value.role === 'seller')
    const cartCount = computed(() => cart.value.length)

    // 检查登录状态
    const checkLogin = () => {
        if (!token.value) {
            ElMessage.warning('请先登录')
            return false
        }
        return true
    }

    // 方法
    const login = async (username: string, password: string, school?: string) => {
        try {
            const response = await apiLogin({ username, password })

            if (response.code === 200) {
                token.value = response.data.token
                userInfo.value = {
                    ...response.data,
                    school: school || response.data.school || '未知学校'
                }
                localStorage.setItem('token', response.data.token)
                localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
                return true
            }
            // 明确返回false，表示登录失败但不是因为网络异常
            return false
        } catch (error) {
            console.error('登录失败:', error)
            // 将错误向上传播，让调用者处理
            throw error
        }
    }

    const logout = () => {
        token.value = ''
        userInfo.value = {}
        products.value = []
        cart.value = []
        favorites.value = []
        chatList.value = []
        unreadCount.value = 0
        walletBalance.value = 0
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
    }

    // 获取用户个人资料
    const getUserProfile = async () => {
        if (!checkLogin()) return false

        try {
            const response = await apiGetUserProfile()
            if (response.code === 200) {
                userInfo.value = { ...userInfo.value, ...response.data }
                walletBalance.value = response.data.balance || 0
                unreadCount.value = response.data.messageCount || 0
                localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
                return true
            }
            return false
        } catch (error) {
            console.error('获取用户资料失败:', error)
            return false
        }
    }

    // 获取用户商品列表
    const getUserProducts = async (params: { page?: number, pageSize?: number, status?: string, userId?: string } = {}) => {
        if (!checkLogin()) return false

        try {
            // 确保总是使用标准格式的参数
            const apiParams = {
                page: params.page || 1,
                pageSize: params.pageSize || 10,
                userId: params.userId || userInfo.value.id,
                status: params.status
            }

            // 删除值为undefined的属性
            if (!apiParams.status) {
                delete apiParams.status;
            }

            // 使用参数字符串作为缓存key
            const cacheKey = JSON.stringify(apiParams);

            // 检查是否有相同请求正在进行中或刚刚完成
            const now = Date.now();
            const cachedRequest = userProductsRequestCache.get(cacheKey);
            if (cachedRequest && (now - cachedRequest.timestamp < REQUEST_CACHE_TIMEOUT)) {
                console.log('使用缓存的用户商品请求结果');
                // 如果已有相同请求，重用上次结果
                return cachedRequest.result;
            }

            productsLoading.value = true;

            // 记录本次请求
            const requestPromise = apiGetUserProducts(apiParams);
            userProductsRequestCache.set(cacheKey, {
                timestamp: now,
                result: requestPromise
            });

            const response = await requestPromise;

            if (response.code === 200) {
                if (apiParams.page === 1) {
                    products.value = response.data.content
                } else {
                    products.value = [...products.value, ...response.data.content]
                }
                productsTotal.value = response.data.totalElements
                return true
            }
            return false
        } catch (error) {
            console.error('获取用户商品列表失败:', error)
            return false
        } finally {
            productsLoading.value = false
        }
    }

    // 获取用户收藏列表
    const getUserFavorites = async () => {
        if (!checkLogin()) return false

        try {
            favoritesLoading.value = true
            console.log('获取用户收藏列表');

            const response = await apiGetUserFavorites();

            console.log('收藏列表响应:', response);

            if (response.code === 200) {
                favorites.value = response.data.content
                favoritesTotal.value = response.data.totalElements
                return true
            } else {
                console.error('获取收藏列表失败:', response.message);
                return false;
            }
        } catch (error) {
            console.error('获取用户收藏列表失败:', error)
            return false
        } finally {
            favoritesLoading.value = false
        }
    }

    const updateUserInfo = async (profile: any) => {
        if (!checkLogin()) return false

        try {
            // 检查是否包含文件类型的头像
            if (profile.avatar instanceof File || (profile.avatarFile && profile.avatarFile instanceof File)) {
                // 创建FormData对象
                const formData = new FormData()

                // 添加文本字段
                for (const key in profile) {
                    if (key !== 'avatar' && key !== 'avatarFile' && key !== 'avatarFilename' && key !== 'avatarType') {
                        formData.append(key, profile[key])
                    }
                }

                // 添加头像文件
                const avatarFile = profile.avatarFile || profile.avatar
                if (avatarFile instanceof File) {
                    formData.append('avatar', avatarFile)
                } else if (profile.avatarFilename && typeof profile.avatarFilename === 'string') {
                    // 如果是已上传的文件名，传递文件名
                    formData.append('avatarFilename', profile.avatarFilename)
                }

                // 发送FormData请求
                const response = await fetch('/api/user/info', {
                    method: 'PUT',
                    headers: {
                        'Authorization': `Bearer ${token.value}`
                    },
                    body: formData
                }).then(res => res.json())

                if (response.code === 200) {
                    userInfo.value = { ...userInfo.value, ...response.data }
                    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
                    return true
                }
                return false
            } else {
                // 无文件的普通请求
                const response = await apiUpdateUserInfo(profile)
                if (response.code === 200) {
                    userInfo.value = { ...userInfo.value, ...response.data }
                    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
                    return true
                }
                return false
            }
        } catch (error) {
            console.error('更新个人信息失败:', error)
            return false
        }
    }

    const addToCart = (product: any) => {
        if (!checkLogin()) return false

        const existingItem = cart.value.find(item => item.id === product.id)
        if (existingItem) {
            existingItem.quantity++
        } else {
            cart.value.push({ ...product, quantity: 1 })
        }
        return true
    }

    const removeFromCart = (productId: number) => {
        if (!checkLogin()) return false

        const index = cart.value.findIndex(item => item.id === productId)
        if (index > -1) {
            cart.value.splice(index, 1)
        }
        return true
    }

    const toggleFavorite = async (product: any) => {
        if (!checkLogin()) return false

        try {
            // 获取用户认证令牌
            const token = localStorage.getItem('token');
            if (!token) {
                console.error('未找到认证令牌');
                return false;
            }

            // 判断当前是否已收藏
            const index = favorites.value.findIndex(item => item.id === product.id);
            const isFavorited = index > -1;

            // 根据当前状态决定是收藏还是取消收藏
            let response;
            if (isFavorited) {
                // 取消收藏
                response = await request.delete(`/products/${product.id}/favorite?userId=${userInfo.value.id}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
            } else {
                // 添加收藏
                response = await request.post(`/products/${product.id}/favorite`, { userId: userInfo.value.id }, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
            }

            // 检查响应是否成功
            if (response && (response.code === 200 || response.status === 200)) {
                // 更新本地收藏列表
                if (isFavorited) {
                    favorites.value.splice(index, 1);
                } else {
                    favorites.value.push(product);
                }

                // 更新商品的收藏状态
                if (product) {
                    product.isFavorite = !isFavorited;
                }

                return true;
            } else {
                console.error('收藏操作失败:', response?.message || '服务器返回错误');
                return false;
            }
        } catch (error) {
            console.error('收藏操作失败:', error);
            return false;
        }
    }

    const addChatMessage = (message: any) => {
        if (!checkLogin()) return false

        chatList.value.push(message)
        if (!message.isRead && message.receiverId === userInfo.value.id) {
            unreadCount.value++
        }
        return true
    }

    const markMessageAsRead = (messageId: number) => {
        if (!checkLogin()) return false

        const message = chatList.value.find(msg => msg.id === messageId)
        if (message && !message.isRead) {
            message.isRead = true
            unreadCount.value = Math.max(0, unreadCount.value - 1)
        }
        return true
    }

    // 更新商品状态
    const updateProductStatus = async (productId: number | string, status: number | string) => {
        if (!checkLogin()) return false

        try {
            const response = await apiUpdateProductStatus(productId, status)
            if (response.code === 200) {
                // 更新本地商品列表
                const index = products.value.findIndex(p => p.id === productId)
                if (index > -1) {
                    products.value[index].status = status
                }
                return true
            }
            return false
        } catch (error) {
            console.error('更新商品状态失败:', error)
            return false
        }
    }

    // 删除商品
    const deleteProduct = async (productId: number | string) => {
        if (!checkLogin()) return false

        try {
            const response = await apiDeleteProduct(productId)
            if (response.code === 200) {
                // 从本地商品列表中移除
                const index = products.value.findIndex(p => p.id === productId)
                if (index > -1) {
                    products.value.splice(index, 1)
                    productsTotal.value = Math.max(0, productsTotal.value - 1)
                }
                return true
            }
            return false
        } catch (error) {
            console.error('删除商品失败:', error)
            return false
        }
    }

    return {
        // 状态
        token,
        userInfo,
        products,
        productsLoading,
        productsTotal,
        cart,
        favorites,
        favoritesLoading,
        favoritesTotal,
        chatList,
        unreadCount,
        walletBalance,

        // 计算属性
        isLoggedIn,
        isSeller,
        cartCount,

        // 方法
        login,
        logout,
        getUserProfile,
        getUserProducts,
        getUserFavorites,
        updateUserInfo,
        addToCart,
        removeFromCart,
        toggleFavorite,
        addChatMessage,
        markMessageAsRead,
        updateProductStatus,
        deleteProduct
    }
}) 